package com.exampl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.exampl.common.R;
import com.exampl.domain.Record;
import com.exampl.domain.User;
import com.exampl.service.RecordService;
import com.exampl.service.UserService;
import com.exampl.utils.SMSUtils;
import com.exampl.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RecordService recordService;

    // 发送验证码
    @PostMapping("/sendMsg")
    public R<String> send(@RequestBody User user, HttpSession session){
        // 注意需要使用user对象进行接收，由于直接使用phone获取得到的值为{phone:phone的值}，得到的不是一个纯号码的字符串
        String phone = user.getPhone();
        if(phone != null){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            // 短信查看验证码
//            SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", phone, code);
            // 控制台查看验证码
            log.info("code = {}", code);
            // 将验证码存储到session中
//            session.setAttribute(phone, code);
            // 将验证码存储到redis中，设置生存时间
            stringRedisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.success("发送成功！");
        }
        return R.error("发送失败！");
    }

    // 登录
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        log.info(map.toString());
        // 获取手机号码
        String phone = map.get("phone").toString();
        // 获取验证码
        String code = map.get("code").toString();
        // 获取验证码
//        Object Code = session.getAttribute(phone);
        String Code = stringRedisTemplate.opsForValue().get(phone);
        // 比对验证码
        if(code.equals(Code)){
            // 判断该手机号是否为新用户
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>();
            lqw.eq(User::getPhone, phone);
            User user = userService.getOne(lqw);
            if(user == null){
                user = new User();
                user.setPhone(phone);
                // 设置用户默认值
                String prefix = UUID.randomUUID().toString();
                prefix = prefix.substring(0, prefix.indexOf("-"));
                user.setName("用户" + prefix);
                user.setSex("2");
                user.setAvatar("headPage.png");
                userService.save(user);
                // 历史记录初始化
                Record record = new Record();
                record.setUserId(user.getId());
                record.setHistory("[]");
                recordService.save(record);
            }
            // 将用户id存入session中，存储user之后，会自动返回id给对象
            session.setAttribute("user", user.getId());
            // 登录成功，删除redis中存储的验证码
            stringRedisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登陆失败！");
    }

    // 退出
    @PostMapping("/loginout")
    public R<String> logout(HttpSession session){
        // 移除user_id
        session.removeAttribute("user");
        return R.success("退出成功！");
    }

    // 返回数据给个人资料
    @GetMapping("update")
    public R<User> update(HttpSession session){
        // 获取用户id
        Long user_id = (Long) session.getAttribute("user");
        User user = userService.getById(user_id);
        System.out.println(user);
        return R.success(user);
    }

    // 提交个人资料
    @PostMapping("submit")
    public R<String> submit(@RequestBody User user, HttpSession session){
        // 获取用户id
        Long user_id = (Long) session.getAttribute("user");
        user.setId(user_id);
        userService.updateById(user);
        return R.success("修改成功！");
    }
}
